package com.basics.common.utils.poi;


import com.basics.common.core.text.Convert;
import com.basics.common.exception.BusinessException;
import com.basics.common.utils.DateUtils;
import com.basics.common.utils.StringUtils;
import com.basics.common.utils.reflect.ReflectUtils;
import com.basics.framework.aspectj.lang.annotation.Excel;
import com.basics.framework.aspectj.lang.annotation.Excels;
import com.basics.framework.config.BasicsConfig;
import com.basics.framework.web.domain.AjaxResult;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

public class ExcelUtil<T> {
    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
    public static final int sheetSize = 65536;
    private String sheetName;
    private Excel.Type type;
    private Workbook wb;
    private Sheet sheet;
    private List<T> list;
    private List<Field> fields;
    public Class<T> clazz;

    public ExcelUtil(Class<T> clazz) {
        this.clazz = clazz;
    }

    public void init(List<T> list, String sheetName, Excel.Type type) {
        if (list == null) {
            list = new ArrayList();
        }

        this.list = (List)list;
        this.sheetName = sheetName;
        this.type = type;
        this.createExcelField();
        this.createWorkbook();
    }

    public List<T> importExcel(InputStream is) throws Exception {
        return this.importExcel("", is);
    }

    public List<T> importExcel(String sheetName, InputStream is) throws Exception {
        this.type = Excel.Type.IMPORT;
        this.wb = WorkbookFactory.create(is);
        List<T> list = new ArrayList();
        Sheet sheet = null;
        if (StringUtils.isNotEmpty(sheetName)) {
            sheet = this.wb.getSheet(sheetName);
        } else {
            sheet = this.wb.getSheetAt(0);
        }

        if (sheet == null) {
            throw new IOException("文件sheet不存在");
        } else {
            int rows = sheet.getPhysicalNumberOfRows();
            if (rows > 0) {
                Map<String, Integer> cellMap = new HashMap();
                Row heard = sheet.getRow(0);

                for(int i = 0; i < heard.getPhysicalNumberOfCells(); ++i) {
                    Cell cell = heard.getCell(i);
                    if (StringUtils.isNotNull(cell != null)) {
                        String value = this.getCellValue(heard, i).toString();
                        cellMap.put(value, i);
                    } else {
                        cellMap.put(null, i);
                    }
                }

                Field[] allFields = this.clazz.getDeclaredFields();
                Map<Integer, Field> fieldsMap = new HashMap();

                int i;
                for(i = 0; i < allFields.length; ++i) {
                    Field field = allFields[i];
                    Excel attr = (Excel)field.getAnnotation(Excel.class);
                    if (attr != null && (attr.type() == Excel.Type.ALL || attr.type() == this.type)) {
                        field.setAccessible(true);
                        Integer column = (Integer)cellMap.get(attr.name());
                        fieldsMap.put(column, field);
                    }
                }

                for(i = 1; i < rows; ++i) {
                    Row row = sheet.getRow(i);
                    T entity = null;
                    Iterator var25 = fieldsMap.entrySet().iterator();

                    while(var25.hasNext()) {
                        Map.Entry<Integer, Field> entry = (Map.Entry)var25.next();
                        Object val = this.getCellValue(row, (Integer)entry.getKey());
                        entity = entity == null ? this.clazz.newInstance() : entity;
                        Field field = (Field)fieldsMap.get(entry.getKey());
                        Class<?> fieldType = field.getType();
                        if (String.class == fieldType) {
                            String s = Convert.toStr(val);
                            if (StringUtils.endsWith(s, ".0")) {
                                val = StringUtils.substringBefore(s, ".0");
                            } else {
                                val = Convert.toStr(val);
                            }
                        } else if (Integer.TYPE != fieldType && Integer.class != fieldType) {
                            if (Long.TYPE != fieldType && Long.class != fieldType) {
                                if (Double.TYPE != fieldType && Double.class != fieldType) {
                                    if (Float.TYPE != fieldType && Float.class != fieldType) {
                                        if (BigDecimal.class == fieldType) {
                                            val = Convert.toBigDecimal(val);
                                        } else if (Date.class == fieldType) {
                                            if (val instanceof String) {
                                                val = DateUtils.parseDate(val);
                                            } else if (val instanceof Double) {
                                                val = DateUtil.getJavaDate((Double)val);
                                            }
                                        }
                                    } else {
                                        val = Convert.toFloat(val);
                                    }
                                } else {
                                    val = Convert.toDouble(val);
                                }
                            } else {
                                val = Convert.toLong(val);
                            }
                        } else {
                            val = Convert.toInt(val);
                        }

                        if (StringUtils.isNotNull(fieldType)) {
                            Excel attr = (Excel)field.getAnnotation(Excel.class);
                            String propertyName = field.getName();
                            if (StringUtils.isNotEmpty(attr.targetAttr())) {
                                propertyName = field.getName() + "." + attr.targetAttr();
                            } else if (StringUtils.isNotEmpty(attr.readConverterExp())) {
                                val = reverseByExp(String.valueOf(val), attr.readConverterExp());
                            }

                            ReflectUtils.invokeSetter(entity, propertyName, val);
                        }
                    }

                    list.add(entity);
                }
            }

            return list;
        }
    }

    public AjaxResult exportExcel(List<T> list, String sheetName) {
        this.init(list, sheetName, Excel.Type.EXPORT);
        return this.exportExcel();
    }

    public AjaxResult importTemplateExcel(String sheetName) {
        this.init((List)null, sheetName, Excel.Type.IMPORT);
        return this.exportExcel();
    }

    public AjaxResult exportExcel() {
        FileOutputStream out = null;

        try {
            double sheetNo = Math.ceil((double)(this.list.size() / 65536));

            for(int index = 0; (double)index <= sheetNo; ++index) {
                this.createSheet(sheetNo, index);
                Row row = this.sheet.createRow(0);
                int excelsNo = 0;

                for(int column = 0; column < this.fields.size(); ++column) {
                    Field field = (Field)this.fields.get(column);
                    if (field.isAnnotationPresent(Excel.class)) {
                        Excel excel = (Excel)field.getAnnotation(Excel.class);
                        this.createCell(excel, row, column);
                    }

                    if (field.isAnnotationPresent(Excels.class)) {
                        Excels attrs = (Excels)field.getAnnotation(Excels.class);
                        Excel[] excels = attrs.value();
                        Excel excel = excels[excelsNo++];
                        this.createCell(excel, row, column);
                    }
                }

                if (Excel.Type.EXPORT.equals(this.type)) {
                    this.fillExcelData(index, row);
                }
            }

            String filename = this.encodingFilename(this.sheetName);
            out = new FileOutputStream(this.getAbsoluteFile(filename));
            this.wb.write(out);
            AjaxResult var25 = AjaxResult.success(filename);
            return var25;
        } catch (Exception var22) {
            log.error("导出Excel异常{}", var22.getMessage());
            throw new BusinessException("导出Excel失败，请联系网站管理员！");
        } finally {
            if (this.wb != null) {
                try {
                    this.wb.close();
                } catch (IOException var21) {
                    var21.printStackTrace();
                }
            }

            if (out != null) {
                try {
                    out.close();
                } catch (IOException var20) {
                    var20.printStackTrace();
                }
            }

        }
    }

    public void fillExcelData(int index, Row row) {
        int startNo = index * 65536;
        int endNo = Math.min(startNo + 65536, this.list.size());
        CellStyle cs = this.wb.createCellStyle();
        cs.setAlignment(HorizontalAlignment.CENTER);
        cs.setVerticalAlignment(VerticalAlignment.CENTER);

        for(int i = startNo; i < endNo; ++i) {
            row = this.sheet.createRow(i + 1 - startNo);
            T vo = this.list.get(i);
            int excelsNo = 0;

            for(int column = 0; column < this.fields.size(); ++column) {
                Field field = (Field)this.fields.get(column);
                field.setAccessible(true);
                if (field.isAnnotationPresent(Excel.class)) {
                    this.addCell((Excel)field.getAnnotation(Excel.class), row, vo, field, column, cs);
                }

                if (field.isAnnotationPresent(Excels.class)) {
                    Excels attrs = (Excels)field.getAnnotation(Excels.class);
                    Excel[] excels = attrs.value();
                    Excel excel = excels[excelsNo++];
                    this.addCell(excel, row, vo, field, column, cs);
                }
            }
        }

    }

    public Cell createCell(Excel attr, Row row, int column) {
        Cell cell = row.createCell(column);
        cell.setCellType(CellType.STRING);
        cell.setCellValue(attr.name());
        CellStyle cellStyle = this.createStyle(attr, row, column);
        cell.setCellStyle(cellStyle);
        return cell;
    }

    public CellStyle createStyle(Excel attr, Row row, int column) {
        CellStyle cellStyle = this.wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font;
        if (attr.name().indexOf("注：") >= 0) {
            font = this.wb.createFont();
            font.setColor((short)10);
            cellStyle.setFont(font);
            cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.YELLOW.getIndex());
            this.sheet.setColumnWidth(column, 6000);
        } else {
            font = this.wb.createFont();
            font.setBold(true);
            cellStyle.setFont(font);
            cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIGHT_YELLOW.getIndex());
            this.sheet.setColumnWidth(column, (int)((attr.width() + 0.72D) * 256.0D));
            row.setHeight((short)((int)(attr.height() * 20.0D)));
        }

        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setWrapText(true);
        if (StringUtils.isNotEmpty(attr.prompt())) {
            this.setXSSFPrompt(this.sheet, "", attr.prompt(), 1, 100, column, column);
        }

        if (attr.combo().length > 0) {
            this.setXSSFValidation(this.sheet, attr.combo(), 1, 100, column, column);
        }

        return cellStyle;
    }

    public Cell addCell(Excel attr, Row row, T vo, Field field, int column, CellStyle cs) {
        Cell cell = null;

        try {
            row.setHeight((short)((int)(attr.height() * 20.0D)));
            if (attr.isExport()) {
                cell = row.createCell(column);
                cell.setCellStyle(cs);
                Object value = this.getTargetValue(vo, field, attr);
                String dateFormat = attr.dateFormat();
                String readConverterExp = attr.readConverterExp();
                if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) {
                    cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date)value));
                } else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value)) {
                    cell.setCellValue(convertByExp(String.valueOf(value), readConverterExp));
                } else {
                    cell.setCellType(CellType.STRING);
                    cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
                }
            }
        } catch (Exception var11) {
            log.error("导出Excel失败{}", var11);
        }

        return cell;
    }

    public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        DataValidation dataValidation = helper.createValidation(constraint, regions);
        dataValidation.createPromptBox(promptTitle, promptContent);
        dataValidation.setShowPromptBox(true);
        sheet.addValidationData(dataValidation);
    }

    public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        DataValidation dataValidation = helper.createValidation(constraint, regions);
        if (dataValidation instanceof XSSFDataValidation) {
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.setShowErrorBox(true);
        } else {
            dataValidation.setSuppressDropDownArrow(false);
        }

        sheet.addValidationData(dataValidation);
    }

    public static String convertByExp(String propertyValue, String converterExp) throws Exception {
        try {
            String[] convertSource = converterExp.split(",");
            String[] var3 = convertSource;
            int var4 = convertSource.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                String item = var3[var5];
                String[] itemArray = item.split("=");
                if (itemArray[0].equals(propertyValue)) {
                    return itemArray[1];
                }
            }

            return propertyValue;
        } catch (Exception var8) {
            throw var8;
        }
    }

    public static String reverseByExp(String propertyValue, String converterExp) throws Exception {
        try {
            String[] convertSource = converterExp.split(",");
            String[] var3 = convertSource;
            int var4 = convertSource.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                String item = var3[var5];
                String[] itemArray = item.split("=");
                if (itemArray[1].equals(propertyValue)) {
                    return itemArray[0];
                }
            }

            return propertyValue;
        } catch (Exception var8) {
            throw var8;
        }
    }

    public String encodingFilename(String filename) {
        filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
        return filename;
    }

    public String getAbsoluteFile(String filename) {
        String downloadPath = BasicsConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }

        return downloadPath;
    }

    private Object getTargetValue(T vo, Field field, Excel excel) throws Exception {
        Object o = field.get(vo);
        if (StringUtils.isNotEmpty(excel.targetAttr())) {
            String target = excel.targetAttr();
            if (target.indexOf(".") > -1) {
                String[] targets = target.split("[.]");
                String[] var7 = targets;
                int var8 = targets.length;

                for(int var9 = 0; var9 < var8; ++var9) {
                    String name = var7[var9];
                    o = this.getValue(o, name);
                }
            } else {
                o = this.getValue(o, target);
            }
        }

        return o;
    }

    private Object getValue(Object o, String name) throws Exception {
        if (StringUtils.isNotEmpty(name)) {
            Class<?> clazz = o.getClass();
            String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method method = clazz.getMethod(methodName);
            o = method.invoke(o);
        }

        return o;
    }

    private void createExcelField() {
        this.fields = new ArrayList();
        List<Field> tempFields = new ArrayList();
        tempFields.addAll(Arrays.asList(this.clazz.getSuperclass().getDeclaredFields()));
        tempFields.addAll(Arrays.asList(this.clazz.getDeclaredFields()));
        Iterator var2 = tempFields.iterator();

        while(true) {
            Field field;
            do {
                if (!var2.hasNext()) {
                    return;
                }

                field = (Field)var2.next();
                if (field.isAnnotationPresent(Excel.class)) {
                    this.putToField(field, (Excel)field.getAnnotation(Excel.class));
                }
            } while(!field.isAnnotationPresent(Excels.class));

            Excels attrs = (Excels)field.getAnnotation(Excels.class);
            Excel[] excels = attrs.value();
            Excel[] var6 = excels;
            int var7 = excels.length;

            for(int var8 = 0; var8 < var7; ++var8) {
                Excel excel = var6[var8];
                this.putToField(field, excel);
            }
        }
    }

    private void putToField(Field field, Excel attr) {
        if (attr != null && (attr.type() == Excel.Type.ALL || attr.type() == this.type)) {
            this.fields.add(field);
        }

    }

    public void createWorkbook() {
        this.wb = new SXSSFWorkbook(500);
    }

    public void createSheet(double sheetNo, int index) {
        this.sheet = this.wb.createSheet();
        if (sheetNo == 0.0D) {
            this.wb.setSheetName(index, this.sheetName);
        } else {
            this.wb.setSheetName(index, this.sheetName + index);
        }

    }

    public Object getCellValue(Row row, int column) {
        if (row == null) {
            return row;
        } else {
            Object val = "";

            try {
                Cell cell = row.getCell(column);
                if (cell != null) {
                    if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                        val = cell.getNumericCellValue();
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            val = DateUtil.getJavaDate((Double)val);
                        } else if ((Double)val % 1.0D > 0.0D) {
                            val = (new DecimalFormat("0.00")).format(val);
                        } else {
                            val = (new DecimalFormat("0")).format(val);
                        }
                    } else if (cell.getCellTypeEnum() == CellType.STRING) {
                        val = cell.getStringCellValue();
                    } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
                        val = cell.getBooleanCellValue();
                    } else if (cell.getCellTypeEnum() == CellType.ERROR) {
                        val = cell.getErrorCellValue();
                    }
                }

                return val;
            } catch (Exception var5) {
                return val;
            }
        }
    }
}

